package com.qhs.sys.controller;

import com.qhs.sys.entity.SysRoleInfo;
import com.qhs.sys.service.MenuService;
import com.qhs.sys.service.RoleService;
import com.qhs.sys.vo.UserVO;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xinchao on 2017/1/12 0012.
 */
@Controller
public class LoginController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;


    @RequestMapping(value = {"/index", "/"})
    public String index(HttpServletRequest request) {
        //TODO 先这么写吧
        Session session = SecurityUtils.getSubject().getSession();
        Long supervisorId = (Long) session.getAttribute("supervisorId");
        Long agencyId = (Long) session.getAttribute("agencyId");
        Long kaId = (Long) session.getAttribute("kaId");
        Long cityAgencyId = (Long) session.getAttribute("cityAgencyId");


        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, HttpServletRequest request) {
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                msg = "密码不正确";
            } else if (AuthenticationException.class.getName().equals(exception)) {
                msg = "用户没有权限登录系统";
            }else if ("kaptchaValidateFailed".equals(exception)) {
                msg = "验证码错误";
            } else {
                msg = "登录异常，请稍后再试";
            }
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            SecurityUtils.getSubject().logout();
            msg = "上次登录未退出，请重新登录";
        }
        model.addAttribute("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理.
        return "login";
    }

    @RequestMapping(value = "userCentre")
    public String userCentre(HttpServletRequest request) {
        UserVO authUser = (UserVO) request.getSession().getAttribute("authUser");
        request.setAttribute("user", authUser);
        List<SysRoleInfo> rolelist = roleService.findRoleListByUserName(authUser.getUserName());
        List<String> roles = new ArrayList<>();
        if (rolelist.size() > 0) {
            for (SysRoleInfo role : rolelist) {
                roles.add(role.getRoleCode());
            }
        }

        return "userCentre";
    }

    /**
     * 设置当前的菜单Id
     */
    @RequestMapping(value = "setCurrentMenuId", method = RequestMethod.POST)
    @ResponseBody
    public String setCurrentMenuId(String pmId, String mid, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("pmId", pmId);
        session.setAttribute("mid", mid);
        UserVO authUser = (UserVO) SecurityUtils.getSubject().getSession().getAttribute("authUser");
        if (authUser != null)
            return "1";
        else return "0";
    }


/*    @RequestMapping(value="/logout",method=RequestMethod.GET)
    public String logout(Model model){
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        model.addAttribute("msg", "您已安全退出");
        return "login";
    }*/

    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public String exception403(HttpServletRequest request) {
        request.setAttribute("message", "权限不足");
        return "403";
    }

}
